package com.xsq.page;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.xsq.BaseApplication;
import com.xsq.Constants;
import com.xsq.R;
import com.xsq.data.ConsumeRecord;
import com.xsq.utils.HttpUtil;
import com.xsq.utils.SharedPreferencesUtils;
import com.xsq.utils.StatusUtils;
import com.xsq.utils.Utils;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

@ContentView(R.layout.fragment_main_report)
public class MainReport extends BaseFragment implements View.OnClickListener {

    private View rootView;
    @ViewInject(R.id.text_date_select_start)
    TextView dateSelectStartTextView;
    @ViewInject(R.id.text_date_select_end)
    TextView dateSelectEndTextView;
    @ViewInject(R.id.btn_submit)
    Button btnSubmit;
    @ViewInject(R.id.refresh_root)
    SmartRefreshLayout refresh_root;
    @ViewInject(R.id.list)
    RecyclerView mListView;

    private LayoutInflater inflater;
    private SharedPreferencesUtils spUtils;
    private Calendar startCalendar;
    private DatePickerDialog startDatePicker;
    private Calendar endCalendar;
    private DatePickerDialog endDatePicker;
    private Gson gson;
    private List<ConsumeRecord> mData;
    private RecordsAdapter mAdapter;

    public static MainReport newInstance() {
        MainReport f = new MainReport();
        Bundle args = new Bundle();
        //args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gson = new Gson();
        startCalendar = Calendar.getInstance();
        endCalendar = Calendar.getInstance();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null) {
            rootView = x.view().inject(this, inflater, container);
        }
        dateSelectStartTextView.setOnClickListener(this);
        dateSelectEndTextView.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        dateSelectStartTextView.setText(Utils.getDateStr(startCalendar.getTime(), "yyyy年MM月dd日"));
        dateSelectEndTextView.setText(Utils.getDateStr(endCalendar.getTime(), "yyyy年MM月dd日"));
        mData = new ArrayList<>();
        mAdapter = new RecordsAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mListView.setLayoutManager(layoutManager);
        mListView.setAdapter(mAdapter);
        refresh_root.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                fetchCardRecords();
            }
        });
        refresh_root.setEnableLoadMore(false);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_date_select_start:
                showStartDatePickerDialog();
                break;
            case R.id.text_date_select_end:
                showEndDatePickerDialog();
                break;
            case R.id.btn_submit:
                fetchCardRecords();
                break;
        }
    }

    private void showStartDatePickerDialog() {
        if(startDatePicker == null) {
            startDatePicker = new DatePickerDialog(getActivity(),
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            startCalendar.set(Calendar.YEAR, year);
                            startCalendar.set(Calendar.MONTH, month);
                            startCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                            dateSelectStartTextView.setText(year + "年" + (month + 1) + "月" + dayOfMonth + "日");
                        }
                    },
                    startCalendar.get(Calendar.YEAR),
                    startCalendar.get(Calendar.MONTH),
                    startCalendar.get(Calendar.DAY_OF_MONTH));
        }
        if(!startDatePicker.isShowing()) {
            startDatePicker.show();
        }
    }

    private void showEndDatePickerDialog() {
        if(endDatePicker == null) {
            endDatePicker = new DatePickerDialog(getActivity(),
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            endCalendar.set(Calendar.YEAR, year);
                            endCalendar.set(Calendar.MONTH, month);
                            endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                            dateSelectEndTextView.setText(year + "年" + (month + 1) + "月" + dayOfMonth + "日");
                        }
                    },
                    endCalendar.get(Calendar.YEAR),
                    endCalendar.get(Calendar.MONTH),
                    endCalendar.get(Calendar.DAY_OF_MONTH));
        }
        if(!endDatePicker.isShowing()) {
            endDatePicker.show();
        }
    }

    private void fetchCardRecords() {
        showDialog("正在查询，请稍候...", 1000);
        String startDate = startCalendar.get(Calendar.YEAR) + "-" + (startCalendar.get(Calendar.MONTH) + 1) + "-" + startCalendar.get(Calendar.DAY_OF_MONTH);
        String endDate = endCalendar.get(Calendar.YEAR) + "-" + (endCalendar.get(Calendar.MONTH) + 1) + "-" + endCalendar.get(Calendar.DAY_OF_MONTH);
        HashMap<String, String> params = new HashMap<>();
        //arams.put("posSn", Utils.getAndroidId(getActivity()));
        params.put("posSn", BaseApplication.getInstance().getWinId());
        params.put("merchantNo", BaseApplication.getInstance().getWinId());
        params.put("windowNo", BaseApplication.getInstance().getWinId());
        params.put("cardNo", ((MainActivity)getActivity()).cardNo);
        params.put("startTime", startDate);
        params.put("endTime", endDate);
        HttpUtil.getInstance().get(BaseApplication.getInstance().getBaseUrl() + Constants.url_queryConsumeRecords, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response==" + response.toString());
                int code = response.optInt("code");
                if(code == 0) {
                    mData.clear();
                    List<ConsumeRecord> records = gson.fromJson(response.optString("records"), new TypeToken<List<ConsumeRecord>>(){}.getType());
                    if(records != null && records.size() > 0) {
                        //merchName.setText(records.get(0).getMerchantName());
                        //merchWind.setText(records.get(0).getWindowName());
                        /*String orderAmountStr = response.optJSONObject("statistic").optString("orderAmount");
                        String actualAmountStr = response.optJSONObject("statistic").optString("actualAmount");
                        String discountAmountStr = response.optJSONObject("statistic").optString("discountAmount");*/
                        //totalOrderAmount.setText(new BigDecimal(orderAmountStr).divide(new BigDecimal(100)) + "元");
                        //totalActualAmount.setText(new BigDecimal(actualAmountStr).divide(new BigDecimal(100)) + "元");
                        //totalDiscountAmount.setText(new BigDecimal(discountAmountStr).divide(new BigDecimal(100)) + "元");
                        showDialog("查询成功", 1000);
                        mData.addAll(records);
                        mAdapter.notifyDataSetChanged();
                    }else {
                        showDialog("没有消费记录", 1000);
                    }
                    refresh_root.finishRefresh();
                }else {
                    showDialog(response.optString("msg"), 1000);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                StatusUtils.handleError(ex, getActivity());
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
				/*String ddddd = "{\n" +
						"    \"msg\": \"操作成功\",\n" +
						"    \"statistic\": {\n" +
						"        \"tradeDate\": \"2019-09-23\",\n" +
						"        \"orderAmount\": 18800,\n" +
						"        \"actualAmount\": 16500,\n" +
						"        \"discountAmount\": 2300,\n" +
						"        \"posSn\": null,\n" +
						"        \"windowNo\": null,\n" +
						"        \"windowName\": null,\n" +
						"        \"merchantNo\": null,\n" +
						"        \"merchantName\": null,\n" +
						"        \"orgCode\": null\n" +
						"    },\n" +
						"    \"code\": 0,\n" +
						"    \"records\": [\n" +
						"        {\n" +
						"            \"recordId\": \"99fcfbaec5354935a73234cca1edf720\",\n" +
						"            \"tradeDate\": \"2019-09-23\",\n" +
						"            \"accountId\": \"3b3acee7b02b4d94b10800f003d53dda\",\n" +
						"            \"userCode\": \"123\",\n" +
						"            \"userType\": \"0\",\n" +
						"            \"userName\": \"张三\",\n" +
						"            \"cardNo\": \"eae44173\",\n" +
						"            \"cardSerialNo\": null,\n" +
						"            \"orderAmount\": 10000,\n" +
						"            \"actualAmount\": 8000,\n" +
						"            \"discountAmount\": 2000,\n" +
						"            \"posSn\": \"85c8da81b96a631c\",\n" +
						"            \"windowNo\": 2,\n" +
						"            \"windowName\": \"2号窗口\",\n" +
						"            \"merchantNo\": 1,\n" +
						"            \"merchantName\": \"肯德基\",\n" +
						"            \"orgCode\": \"PLA-NJACC\",\n" +
						"            \"createGmt\": \"2019-09-23 22:34:51\",\n" +
						"            \"updateGmt\": null\n" +
						"        },\n" +
						"        {\n" +
						"            \"recordId\": \"4b1c6ac120974e24adfee2bcb17d5687\",\n" +
						"            \"tradeDate\": \"2019-09-23\",\n" +
						"            \"accountId\": \"3b3acee7b02b4d94b10800f003d53dda\",\n" +
						"            \"userCode\": \"123\",\n" +
						"            \"userType\": \"0\",\n" +
						"            \"userName\": \"张三\",\n" +
						"            \"cardNo\": \"eae44173\",\n" +
						"            \"cardSerialNo\": null,\n" +
						"            \"orderAmount\": 8800,\n" +
						"            \"actualAmount\": 8500,\n" +
						"            \"discountAmount\": 300,\n" +
						"            \"posSn\": \"85c8da81b96a631c\",\n" +
						"            \"windowNo\": 2,\n" +
						"            \"windowName\": \"2号窗口\",\n" +
						"            \"merchantNo\": 1,\n" +
						"            \"merchantName\": \"肯德基\",\n" +
						"            \"orgCode\": \"PLA-NJACC\",\n" +
						"            \"createGmt\": null,\n" +
						"            \"updateGmt\": null\n" +
						"        }\n" +
						"    ]\n" +
						"}";
				try {
					JSONObject response = new JSONObject(ddddd);
					int code = response.optInt("code");
					if(code == 0) {
						mData.clear();
						Gson gson = new Gson();
						List<Records> records = gson.fromJson(response.optString("records"), new TypeToken<List<Records>>(){}.getType());
						if(records != null && records.size() > 0) {
							merchName.setText(records.get(0).getMerchantName());
							merchWind.setText(records.get(0).getWindowName());
							totalOrderAmount.setText(response.optJSONObject("statistic").optString("orderAmount"));
							totalActualAmount.setText(response.optJSONObject("statistic").optString("actualAmount"));
							totalDiscountAmount.setText(response.optJSONObject("statistic").optString("discountAmount"));
							mData.addAll(records);
							mAdapter.notifyDataSetChanged();
						}
						refresh_root.finishRefresh();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}*/
                refresh_root.finishRefresh();
            }
        });
    }

    private class RecordsAdapter extends RecyclerView.Adapter {

        public RecordsAdapter() {
            inflater = LayoutInflater.from(getActivity());
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            RecordsViewHolder viewHolder = new RecordsViewHolder(inflater.inflate(R.layout.adapter_records, viewGroup, false));
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            final ConsumeRecord item = mData.get(i);
            RecordsAdapter.RecordsViewHolder holder = (RecordsAdapter.RecordsViewHolder)viewHolder;
            holder.code.setText(Utils.trimSpace(item.getUSERCODE()));
            holder.username.setText(Utils.trimSpace(item.getUSERNAME()));
            holder.winNo.setText(String.valueOf(item.getWINNO()));
            holder.winName.setText(Utils.trimSpace(item.getWINNAME()));
            holder.money.setText(String.valueOf(item.getTRANSACTMONEY()));
            holder.type.setText(Utils.trimSpace(item.getTYPENAME()));
            holder.time.setText(Utils.formatTime(item.getCONSUMETIME()));
            holder.operate.setText("--");
            //holder.actualAmountText.setText(new BigDecimal(item.getTRANSACTMONEY()).divide(new BigDecimal(100)) + "元");
            //holder.actualAmountText.setText(item.getTRANSACTMONEY() + "元");
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }

        class RecordsViewHolder extends RecyclerView.ViewHolder {

            private TextView code;
            private TextView username;
            private TextView winNo;
            private TextView winName;
            private TextView money;
            private TextView type;
            private TextView time;
            private TextView operate;
            public RecordsViewHolder(@NonNull View itemView) {
                super(itemView);
                code = itemView.findViewById(R.id.item_code);
                username = itemView.findViewById(R.id.item_username);
                winNo = itemView.findViewById(R.id.item_win_no);
                winName = itemView.findViewById(R.id.item_win_name);
                money = itemView.findViewById(R.id.item_money);
                type = itemView.findViewById(R.id.item_type);
                time = itemView.findViewById(R.id.item_time);
                operate = itemView.findViewById(R.id.item_operate);
            }
        }
    }
}
